package com.ljfresh.customer.utils.udesk;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/*import com.framework.loippi.utils.JacksonUtil;
import com.framework.loippi.utils.sync.param.OrderCreateParam;
import com.framework.loippi.utils.sync.param.OrderRefundParam;*/
import com.ljfresh.customer.pojo.Attachment;
import com.ljfresh.customer.pojo.Ticket;
import com.ljfresh.customer.pojo.TicketField;
import com.ljfresh.customer.pojo.WorkOrder;
import com.ljfresh.customer.utils.base.Dateutil;
import com.ljfresh.customer.utils.base.JacksonUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;

import java.net.URLEncoder;
import java.util.*;

/**
 * Created by z on 2018/12/13.
 * erp接口参数生成
 */
public class UDeskParamBuilder {
    /**
     * 加签
     * @param map
     * @return
     */
    private static String sign(Map<String, Object> map, String secret){
        if(map==null){
            return null;
        }
        List<String> keyList = new ArrayList<>(map.keySet());
        Collections.sort(keyList);
        StringBuilder sb = new StringBuilder();
        sb.append(secret);
        for(int i=0;i<keyList.size();i++){
            String key = keyList.get(i);
            Object value = map.get(key);
            sb.append(key+value);
        }
        sb.append(secret);
        String sign = sb.toString();
        //System.out.println("before sign: "+sign);
        String md5Str = DigestUtils.md5Hex(sign);
        //System.out.println("after sign: "+md5Str);
        return md5Str;
    }


/*    *//**
     * 加签 含&
     * @param map
     * @return
     *//*
    private static String signWithAnd(Map<String, Object> map, String secret){
        if(map==null){
            return null;
        }
        List<String> keyList = new ArrayList<>(map.keySet());
        Collections.sort(keyList);
        StringBuilder sb = new StringBuilder();
        sb.append(secret);
        Integer size = keyList.size();
        for(int i=0;i< size;i++){
            String key = keyList.get(i);
            Object value = map.get(key);
            sb.append(key+"="+value);
            if(i < size-1){
                sb.append("&");
            }
        }
        sb.append(secret);
        String sign = sb.toString();
        //System.out.println("before sign: "+sign);
        String md5Str = DigestUtils.md5Hex(sign);
        //System.out.println("after sign: "+md5Str);
        return md5Str;
    }*/

    /**
     * 请求参数拼接
     * @param map
     * @return
     */
    private static String paramStr(Map<String, Object> map){
        if(map==null){
            return null;
        }
        List<String> keyList = new ArrayList<>(map.keySet());
        Collections.sort(keyList);
        Integer size = keyList.size();
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<size;i++){
            String key = keyList.get(i);
            Object value = map.get(key);
            sb.append(key+"="+value);
            if(i < size-1){
                sb.append("&");
            }
        }
        return sb.toString();
    }

    /**
     * 非空put
     * @param map
     * @param key
     * @param value
     */
    private static void putIfNotEmpty(Map<String, Object> map, String key, Object value) {
        String str = ObjectUtils.toString(value, "");
        if (StringUtils.isNotEmpty(str) && !"null".equals(value)) {
            map.put(key, value);
        }
    }


    public static String generateUDeskParam(String method, String paramType){
        Map<String,Object> param = new HashMap<>();
        param.put("method",method);
        param.put("timestamp", Dateutil.toString(new Date(),Dateutil.NORMAL_FORMAT));
        //32位MD5加密
        String md5Str = sign(param,paramType);
        param.put("sign",md5Str);
        return paramStr(param);
    }

    /**
     * 查询工单详情接口

     * @return
     */
    public static String generateDetailParam(Integer id, String num){
        Map<String,Object> param = new HashMap<>();
        try{
            if(StringUtils.isNotEmpty(num)){
                param.put("num", URLEncoder.encode(num,"GBK"));
            }else if (id !=null){
                param.put("id", id);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        handleURLParam(param);
        return paramStr(param);
    }

    /**
     * 创建只有加密数据的接口路径
     * @return
     */
    public static String generateURLParam(){
        Map<String,Object> param = new HashMap<>();
        handleURLParam(param);
        return paramStr(param);
    }


    /**
     * 获取工单过滤器列表

     * @return
     */
    public static String generateFiltersParam(String type,Integer id,Integer page,Integer per_page){
        Map<String,Object> param = new HashMap<>();
        if(StringUtils.isNotEmpty(type)){
            param.put("type",type);
            if (!type.equals("all")){
                param.put("id",id);
            }
        }
        if (page!=null && per_page!=null){
            handlePageParam(page,per_page,param);
        }
        handleURLParam(param);
        return paramStr(param);
    }


    /**
     * 获取特定工单过滤器下的工单
     * @return
     */
    public static String generateTicketInFiltersParam(Integer filters,Integer page,Integer per_page){
        Map<String,Object> param = new HashMap<>();
        if (filters == null){
            return "";//返回错误状态码
        }
            param.put("filter_id",filters);
        handlePageParam(page,per_page,param);
        handleURLParam(param);
        return paramStr(param);
    }

    /**
     * 工单上传附件

     * @return
     */
    public static String generateUploadFileParam(Integer ticketId,String fileName,String type){
        Map<String,Object> param = new HashMap<>();
        if (ticketId == null){
            return "";//返回错误状态码
        }
        param.put("ticket_id",ticketId);
        if (fileName !=null){
            param.put("file_name", fileName);
        }
        if (type !=null){
            param.put("type", type);
        }
        handleURLParam(param);
        return paramStr(param);
    }

    /**
     * 工单上传附件清除
     * @return
     */
    public static String generateDeleteFileForReplyParam(Integer ticketId){
        Map<String,Object> param = new HashMap<>();
        if (ticketId == null){
            return "";//返回错误状态码
        }
        param.put("ticket_id",ticketId);
        handleURLParam(param);
        return paramStr(param);
    }

    /**
     * 工单上传附件清除
     * @return
     */
    public static String generateDeleteFileForReplyParam(Integer ticketId,String fileName,String type){
        Map<String,Object> param = new HashMap<>();
        if (ticketId == null){
            return "";//返回错误状态码
        }
        param.put("ticket_id",ticketId);
        if (fileName !=null){
            param.put("file_name", fileName);
        }
        if (type !=null){
            param.put("type", type);
        }
        handleURLParam(param);
        return paramStr(param);
    }

    /**
     * 获取客户记录

     * @return
     */
    public static String generateCustomRecordParam(String type,String content,Integer page,Integer per_page){
        Map<String,Object> param = new HashMap<>();
        if(StringUtils.isNotEmpty(type)){
            param.put("type",type);
            param.put("content",content);
        }
        handlePageParam(page,per_page,param);
        handleURLParam(param);
        return paramStr(param);
    }

    /**
     * 获取客户记录

     * @return
     */
    public static String generateCustomParam(String type,String content){
        Map<String,Object> param = new HashMap<>();
        if(StringUtils.isNotEmpty(type)){
            param.put("type",type);
            param.put("content",content);
        }
        handleURLParam(param);
        return paramStr(param);
    }

    /**
     * 客服发送回复

     * @return
     */
    public static String generateCustomerReplyParam(Integer id, String num, String newReply, String contentType, List<Long> attachment_ids){
        Map<String,Object> param = new HashMap<>();
        if (id == null && num == null){
            return "";//返回错误状态码
        }
        param.put("newReply",newReply);
        if (contentType !=null){
            param.put("contentType", contentType);
        }
        if (attachment_ids !=null && attachment_ids.size()!=0){
            param.put("type", attachment_ids);
        }
        handleURLParam(param);
        return paramStr(param);
    }

    /**
     * 客服发送回复

     * @return
     */
    public static String generateTicketTemplatesParam(){
        Map<String,Object> param = new HashMap<>();
        handleURLParam(param);
        return paramStr(param);
    }

    public static String generateGetAllReplyParam(Integer pageNum,Integer pageSize) {
        Map<String,Object> param = new HashMap<>();
        handlePageParam(pageNum,pageSize,param);
        handleURLParam(param);
        return paramStr(param);
    }

    /**
     * 抽出分页方法
     * @param page
     * @param per_page
     * @param param
     */
    private static void handlePageParam(Integer page,Integer per_page,Map<String,Object> param) {
        if (page !=null){
            param.put("page", page);
        }
        if (per_page !=null){
            param.put("page_size", per_page);
        }
    }

    /**
     * 抽出URL通用参数
     * @param param
     */
    private static void handleURLParam(Map<String,Object> param) {
        param.put("email",UDeskConst.UDESK_ADMIN_EMAIL);
        String timestamp = Long.toString(System.currentTimeMillis()/1000L);
        param.put("timestamp",timestamp);
        String nonce = UUID.randomUUID().toString();
        param.put("nonce",nonce);
        //SHA256加密
        String sign = SHA256Util.getSHA256StrJava(UDeskConst.UDESK_ADMIN_EMAIL+"&"+UDeskConst.UDESK_API_TOKEN+"&"+ timestamp +"&"+ nonce+"&"+UDeskConst.SIGN_VERSION);
        param.put("sign",sign);
        param.put("sign_version","v2");
    }


}
